<template>
	<view class="">
		<canvas v-show="!qrcode_src" canvas-id="qrcode"  style="position: fixed; top: 10000px; left: 10000px;"  :style="{width:(width + unit), height:(height + unit)}" />
		<image v-if='show' :src="qrcode_src" :style="{width:(width + unit), height:(height + unit)}"></image>
	</view>
</template>

<script>
	import qrcode from './lib/qrcode.js'
	export default {
		name: "my-qrcode",
		data() {
			return {
				qrcode_src: ''
			}
		},
		props: {
			code: {
				type: String,
				default: ''
			},
			width: {
				type: Number,
				default: 200
			},
			height: {
				type: Number,
				default: 200
			},
			unit: {
				type: String,
				default: 'rpx'
			},
			padding: {
				type: Number,
				default: 0
			},
			// 图片预览
			show:{
				type: Boolean,
				default: false
			}
		},
		watch: {
			code: function(newVal, oldVal) {
				if (Boolean(newVal)) {
					setTimeout(() => {
						this.toQrcode();
					}, 0)
				}
			}
		},
		mounted: function() {
			if (Boolean(this.code)) {
				setTimeout(() => {
					this.toQrcode();
				}, 0)
			}
		},
		methods: {
			// 插件内部是根据width, height参数的px值来进行绘画
			// 把数字转换成二维码
			toQrcode: function() {
				let width = this.unit == 'px' ? this.width : uni.upx2px(this.width);
				let height = this.unit == 'px' ? this.height : uni.upx2px(this.height);
				qrcode.api.top = 0;
				qrcode.api.left = 0;
				qrcode.api.padding = (this.unit == 'px' ? Number(this.padding) : uni.upx2px(this.padding));
				qrcode.api.draw(this.code, uni.createCanvasContext('qrcode', this), width, height, this.callback)
			},
			
			callback: function(){
				console.log('绘制二维码结束')
				// 生成图片
				let width = this.unit == 'px' ? this.width : uni.upx2px(this.width);
				let height = this.unit == 'px' ? this.height : uni.upx2px(this.height);
				let that = this;
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: width,
					height: height,
					destWidth: 2 * width,
					destHeight: 2 * height,
					canvasId: 'qrcode',
					success: function(res) {
						// console.log(res.tempFilePath)
						// 在 H5平台下，tempFilePath 为 base64
						that.qrcode_src = res.tempFilePath
						that.$emit('onDone', that.qrcode_src);
					},
					fail: function(error){
						console.log(error);
					}
				}, this)
			}
		},
	}
</script>
<style>
</style>
